import ttkbootstrap as ttkb
from ttkbootstrap.constants import *
from tkinter import messagebox, filedialog, ttk
import json
from datetime import datetime
from data_manager.db_handler import (
    get_tasks_by_project, create_task, update_task, delete_tasks, batch_update_tasks
)

class TaskPanel(ttkb.Frame):
    def __init__(self, parent, on_task_operate):
        super().__init__(parent, padding=(10, 10))
        self.parent = parent  # 父容器（left_vertical_pane）
        self.on_task_operate = on_task_operate  # 任务操作回调
        self.is_editing = False  # 编辑状态标记（关闭校验用）
        self._build_ui()

    def _build_ui(self):
        """任务面板UI：筛选+列表+按钮（Windows 字体适配）"""
        # 1. 标题栏
        self.title_frame = ttkb.Frame(self)
        self.title_frame.pack(fill=X, anchor=N, pady=(0, 10))
        self.title_label = ttkb.Label(self.title_frame, text="任务列表")
        self.title_label.pack(side=LEFT)

        # 2. 筛选栏（优先级+状态+负责人+搜索）
        self.filter_frame = ttkb.Frame(self)
        self.filter_frame.pack(fill=X, anchor=N, pady=(0, 8))

        # 优先级筛选
        self.priority_var = ttkb.StringVar(value="all")
        self.priority_label = ttkb.Label(self.filter_frame, text="优先级：")
        self.priority_label.pack(side=LEFT)
        self.priority_combo = ttkb.Combobox(
            self.filter_frame, textvariable=self.priority_var,
            values=["all", "高", "中", "低"], state="readonly", width=8
        )
        self.priority_combo.pack(side=LEFT, padx=5)
        self.priority_combo.bind("<<ComboboxSelected>>", self._on_filter_change)

        # 状态筛选
        self.status_var = ttkb.StringVar(value="all")
        self.status_label = ttkb.Label(self.filter_frame, text="状态：")
        self.status_label.pack(side=LEFT, padx=(10, 0))
        self.status_combo = ttkb.Combobox(
            self.filter_frame, textvariable=self.status_var,
            values=["all", "未开始", "进行中", "已完成", "延期"], state="readonly", width=8
        )
        self.status_combo.pack(side=LEFT, padx=5)
        self.status_combo.bind("<<ComboboxSelected>>", self._on_filter_change)

        # 负责人筛选
        self.owner_var = ttkb.StringVar(value="all")
        self.owner_label = ttkb.Label(self.filter_frame, text="负责人：")
        self.owner_label.pack(side=LEFT, padx=(10, 0))
        self.owner_combo = ttkb.Combobox(
            self.filter_frame, textvariable=self.owner_var,
            values=["all"], state="readonly", width=12
        )
        self.owner_combo.pack(side=LEFT, padx=5)
        self.owner_combo.bind("<<ComboboxSelected>>", self._on_filter_change)
        self.divider = ttkb.Separator(self, orient=HORIZONTAL)
        self.divider.pack(fill=X, pady=(0, 8))
        
        # 搜索框（Windows 中文适配）
        self.search_var = ttkb.StringVar()
        self.search_entry = ttkb.Entry(
            self.filter_frame, textvariable=self.search_var,
            width=30
        )
        self.search_entry.pack(side=LEFT, padx=10)
        # 使用placeholder的替代方案
        self.search_entry.insert(0, "搜索任务名称/描述...")
        self.search_entry.configure(foreground='#808080')  # 浅灰色文字
        # 绑定搜索框事件
        self.search_entry.bind('<FocusIn>', self._on_search_focus_in)
        self.search_entry.bind('<FocusOut>', self._on_search_focus_out)
        self.search_entry.bind('<KeyRelease>', self._on_search_input)
        self.search_entry.pack(side=LEFT, padx=(0, 8), fill=X, expand=YES)
        
        self.search_btn = ttkb.Button(
            self.filter_frame, text="搜索", command=self._on_search,
            bootstyle=PRIMARY, width=8
        )
        self.search_btn.pack(side=LEFT)
        
        self.reset_btn = ttkb.Button(
            self.filter_frame, text="重置", command=self._reset_filter,
            bootstyle=OUTLINE, width=8
        )
        self.reset_btn.pack(side=LEFT, padx=(0, 8))
        
        # 3. 操作按钮
        self.btn_frame = ttkb.Frame(self)
        self.btn_frame.pack(fill=X, anchor=N, pady=(0, 8))

        self.create_btn = ttkb.Button(
            self.btn_frame, text="新建任务", command=self.create_task,
            bootstyle=SUCCESS, width=12
        )
        self.create_btn.pack(side=LEFT)

        self.edit_btn = ttkb.Button(
            self.btn_frame, text="编辑任务", command=self.edit_task,
            bootstyle=PRIMARY, width=12, state=DISABLED
        )
        self.edit_btn.pack(side=LEFT, padx=5)

        self.delete_btn = ttkb.Button(
            self.btn_frame, text="删除选中", command=self.delete_selected_tasks,
            bootstyle=DANGER, width=12, state=DISABLED
        )
        self.delete_btn.pack(side=LEFT, padx=5)

        self.batch_edit_btn = ttkb.Button(
            self.btn_frame, text="批量修改", command=self.batch_edit_task,
            bootstyle=INFO, width=12, state=DISABLED
        )
        self.batch_edit_btn.pack(side=LEFT, padx=5)
        
        # 4. 任务列表（带复选框，Windows 滚动适配）
        self.list_frame = ttkb.Frame(self)
        self.list_frame.pack(fill=BOTH, expand=YES)
        
        self.scrollbar_y = ttkb.Scrollbar(self.list_frame, orient=VERTICAL)
        self.scrollbar_x = ttkb.Scrollbar(self.list_frame, orient=HORIZONTAL)
        
        self.task_tree = ttk.Treeview(
            self.list_frame, 
            columns=("select", "name", "priority", "owner", "start", "end", "status", "progress"),
            show="headings", 
            yscrollcommand=self.scrollbar_y.set,
            xscrollcommand=self.scrollbar_x.set,
            selectmode="extended"
        )
        
        self.scrollbar_y.config(command=self.task_tree.yview)
        self.scrollbar_x.config(command=self.task_tree.xview)
        
        # 列配置（Windows 分辨率适配）
        self.task_tree.heading("select", text="选择", anchor=CENTER)
        self.task_tree.heading("name", text="任务名称", anchor=W)
        self.task_tree.heading("priority", text="优先级", anchor=CENTER)
        self.task_tree.heading("owner", text="负责人", anchor=CENTER)
        self.task_tree.heading("start", text="开始日期", anchor=CENTER)
        self.task_tree.heading("end", text="计划结束", anchor=CENTER)
        self.task_tree.heading("status", text="状态", anchor=CENTER)
        self.task_tree.heading("progress", text="进度(%)", anchor=CENTER)
        
        self.task_tree.column("select", width=60, stretch=NO)
        self.task_tree.column("name", width=200, stretch=YES)
        self.task_tree.column("priority", width=80, stretch=NO)
        self.task_tree.column("owner", width=120, stretch=NO)
        self.task_tree.column("start", width=120, stretch=NO)
        self.task_tree.column("end", width=120, stretch=NO)
        self.task_tree.column("status", width=100, stretch=NO)
        self.task_tree.column("progress", width=100, stretch=NO)
        
        # 绑定事件
        self.task_tree.bind("<<TreeviewSelect>>", self._on_task_select)
        self.task_tree.bind("<Double-1>", self._on_task_double_click)
        
        # 添加入选框（Windows 渲染适配）
        self._add_checkbox_column()
        
        # 布局
        self.scrollbar_y.pack(side=RIGHT, fill=Y)
        self.scrollbar_x.pack(side=BOTTOM, fill=X)
        self.task_tree.pack(fill=BOTH, expand=YES)

    def _add_checkbox_column(self):
        """复选框列：Windows 滚动后不消失"""
        self.checkboxes = {}  # key: task_id（整数）, value: BooleanVar
        
        def render_checkbox(tree, row, column):
            """渲染复选框到单元格（避免重复创建）"""
            task_id = int(row)  # 强制整数
            if task_id not in self.checkboxes:
                self.checkboxes[task_id] = ttkb.BooleanVar()
            
            # 清除现有控件（避免重叠）
            for widget in tree.winfo_children():
                if widget.winfo_name() == f"chk_{task_id}":
                    widget.destroy()
            
            # 创建复选框（Windows 风格：round-toggle）
            chk = ttkb.Checkbutton(
                tree, variable=self.checkboxes[task_id],
                name=f"chk_{task_id}", bootstyle="round-toggle"
            )
            # 定位（Windows 像素适配）
            bbox = tree.bbox(row, column)
            if bbox:  # 确保单元格存在
                chk.place(
                    x=bbox[0] + 22, y=bbox[1] + 2,
                    width=16, height=16
                )
        
        # 监听滚动/展开事件，重新渲染复选框
        self.task_tree.bind("<Expose>", lambda e: self._render_all_checkboxes())
        self.task_tree.bind("<<TreeviewOpen>>", lambda e: self._render_all_checkboxes())

    def _render_all_checkboxes(self):
        """重新渲染所有复选框（Windows 滚动适配）"""
        for task_id in self.checkboxes:
            if self.task_tree.exists(int(task_id)):  # 确认任务行存在
                render_checkbox(self.task_tree, int(task_id), "select")

    def load_tasks(self, project_id):
        """加载任务：ID 为整数，Windows 数据适配"""
        # 清空数据
        for item in self.task_tree.get_children():
            self.task_tree.delete(item)
        self.checkboxes.clear()
        self.is_editing = False
        
        # 获取任务（project_id 强制整数）
        all_tasks = get_tasks_by_project(int(project_id))
        if not all_tasks:
            self.edit_btn.config(state=DISABLED)
            self.delete_btn.config(state=DISABLED)
            self.batch_edit_btn.config(state=DISABLED)
            self.owner_combo.config(values=["all"])
            return []
        
        # 应用筛选
        filtered_tasks = self._apply_filter(all_tasks)
        
        # 更新负责人下拉框
        owners = list({task[4] for task in all_tasks if task[4]})  # 去重非空
        self.owner_combo.config(values=["all"] + sorted(owners))
        
        # 插入任务（ID 为整数，样式适配 Windows 主题）
        for task in filtered_tasks:
            (task_id, name, priority, owner, start_date, end_date, 
             status, progress, description, dependency) = task
            
            # 优先级样式（Windows 颜色适配）
            priority_tag = f"p_{priority}"
            if priority_tag not in self.task_tree.tag_names():
                color_map = {"高": "red", "中": "orange", "低": "green"}
                self.task_tree.tag_configure(priority_tag, foreground=color_map[priority])
            
            # 状态样式
            status_tag = f"s_{status}"
            if status_tag not in self.task_tree.tag_names():
                color_map = {"已完成": "gray", "延期": "red", "进行中": "blue", "未开始": "black"}
                self.task_tree.tag_configure(status_tag, foreground=color_map[status])
            
            # 插入行（iid 为整数）
            self.task_tree.insert(
                "", END, iid=int(task_id),
                values=("", name, priority, owner, start_date, end_date, status, progress),
                tags=(priority_tag, status_tag)
            )
        
        # 渲染复选框
        self._render_all_checkboxes()
        
        # 激活按钮
        self.edit_btn.config(state=NORMAL if filtered_tasks else DISABLED)
        self.delete_btn.config(state=NORMAL if filtered_tasks else DISABLED)
        self.batch_edit_btn.config(state=NORMAL if filtered_tasks else DISABLED)
        
        return filtered_tasks

    def _apply_filter(self, tasks):
        """筛选任务：忽略大小写，适配 Windows 中文输入"""
        priority = self.priority_var.get().strip()
        status = self.status_var.get().strip()
        owner = self.owner_var.get().strip()
        search_key = self.search_var.get().strip().lower()
        
        filtered = []
        for task in tasks:
            (task_id, name, task_priority, task_owner, start_date, end_date, 
             task_status, progress, desc, dependency) = task
            
            # 优先级筛选
            if priority != "all" and task_priority != priority:
                continue
            # 状态筛选
            if status != "all" and task_status != status:
                continue
            # 负责人筛选
            if owner != "all" and task_owner != owner:
                continue
            # 搜索筛选（中文适配）
            if search_key and (search_key not in name.lower() and search_key not in desc.lower()):
                continue
            
            filtered.append(task)
        
        return filtered

    # ---------------------- 筛选/搜索功能 ----------------------
    def _on_filter_change(self, event):
        """筛选变化：获取当前项目ID（父窗口层级适配）"""
        # 父窗口层级：task_panel -> left_vertical_pane -> horizontal_pane -> main_window
        main_window = self.parent.master.master
        project_id = main_window.current_project_id if hasattr(main_window, "current_project_id") else None
        if project_id:
            self.load_tasks(project_id)

    def _on_search(self):
        self._on_filter_change(None)

    def _reset_filter(self):
        self.priority_var.set("all")
        self.status_var.set("all")
        self.owner_var.set("all")
        self.search_var.set("")
        self._on_filter_change(None)

    # ---------------------- 任务操作功能 ----------------------
    def create_task(self):
        """新建任务：获取当前项目ID并修复刷新机制"""
        # 获取主窗口（正确的层级关系：task_panel -> left_vertical_pane -> horizontal_pane -> main_window）
        if self.parent and hasattr(self.parent, "master") and hasattr(self.parent.master, "master"):
            main_window = self.parent.master.master
            project_id = main_window.current_project_id if hasattr(main_window, "current_project_id") else None
            
            if not project_id:
                messagebox.showwarning("操作提示", "请先选择一个项目", parent=self)
                return
            
            from ui_components.dialogs import TaskFormDialog
            self.is_editing = True
            dialog = TaskFormDialog(self, title="新建任务", action="create")
            self.is_editing = False
            
            if dialog.result:
                create_task(project_id=int(project_id), **dialog.result)
                
                # 调用主窗口的全局刷新方法，确保所有面板同步更新
                if main_window and hasattr(main_window, "_refresh_all_panels"):
                    main_window._refresh_all_panels()
                    print("[DEBUG] 任务创建后已调用主窗口的_refresh_all_panels()方法")
                else:
                    # 如果无法直接调用全局刷新，回退到使用回调
                    self.on_task_operate("create", dialog.result)
                    print("[DEBUG] 无法调用全局刷新，使用回调方法刷新")
                
                messagebox.showinfo("操作成功", f"任务「{dialog.result['task_name']}」创建完成并已显示在任务列表中", parent=self)
        else:
            print("[DEBUG] 无法获取主窗口，任务创建可能无法正常显示")
            messagebox.showwarning("警告", "无法获取系统上下文，任务创建可能无法正常显示", parent=self)

    def _on_task_double_click(self, event):
        """处理任务双击事件：编辑任务"""
        # 确保点击的是任务项而不是表头
        region = self.task_tree.identify_region(event.x, event.y)
        if region != 'cell':
            return
        
        # 调用编辑任务方法
        self.edit_task()

    def edit_task(self):
        """编辑任务：ID 整数匹配"""
        selected_items = self.task_tree.selection()
        if len(selected_items) != 1:
            messagebox.showwarning("操作提示", "请选择一个任务进行编辑", parent=self)
            return
        
        task_id = int(selected_items[0])  # 转整数
        # 从主窗口缓存获取任务（减少查库）
        main_window = self.parent.master.master
        task_cache = main_window.task_cache if hasattr(main_window, "task_cache") else []
        task = next((t for t in task_cache if t[0] == task_id), None)
        if not task:
            messagebox.showwarning("数据错误", "任务数据不存在", parent=self)
            return
        
        # 组装任务数据
        task_data = {
            "task_name": task[1],
            "priority": task[2],
            "owner": task[3],
            "start_date": task[4],
            "end_date": task[5],
            "status": task[6],
            "progress": task[7],
            "description": task[8],
            "dependency": task[9]
        }
        
        from ui_components.dialogs import TaskFormDialog
        self.is_editing = True
        dialog = TaskFormDialog(self, title="编辑任务", action="edit", init_data=task_data)
        self.is_editing = False
        
        if dialog.result:
            update_task(task_id, **dialog.result)
            self.on_task_operate("edit", dialog.result)
            messagebox.showinfo("操作成功", "任务信息更新完成", parent=self)

    def delete_selected_tasks(self):
        """删除任务：批量整数 ID"""
        selected_items = self.task_tree.selection()
        if not selected_items:
            messagebox.showwarning("操作提示", "请选择至少一个任务", parent=self)
            return
        
        confirm = messagebox.askyesno(
            "危险操作", f"确定要删除选中的 {len(selected_items)} 个任务吗？",
            parent=self, icon=messagebox.WARNING
        )
        if confirm:
            task_ids = [int(item) for item in selected_items]  # 转整数列表
            delete_tasks(task_ids)
            self.on_task_operate("delete")
            messagebox.showinfo("操作成功", f"{len(selected_items)} 个任务已删除", parent=self)

    def batch_edit_task(self):
        """批量修改：整数 ID 列表"""
        selected_items = self.task_tree.selection()
        if not selected_items:
            messagebox.showwarning("操作提示", "请选择至少一个任务", parent=self)
            return
        
        from ui_components.dialogs import BatchTaskDialog
        dialog = BatchTaskDialog(self, title=f"批量修改（{len(selected_items)} 个任务）")
        if dialog.result:
            task_ids = [int(item) for item in selected_items]
            batch_update_tasks(task_ids, **dialog.result)
            self.on_task_operate("batch_edit")
            messagebox.showinfo("操作成功", f"{len(selected_items)} 个任务已批量更新", parent=self)

    def import_json(self, project_id):
        """导入 JSON：Windows 文件路径适配"""
        file_path = filedialog.askopenfilename(
            title="选择JSON文件（Windows）", 
            filetypes=[("JSON Files", "*.json"), ("All Files", "*.*")], 
            parent=self,
            initialdir="C:/Users/Administrator/Desktop"  # Windows 桌面路径
        )
        if not file_path:
            return
        
        try:
            with open(file_path, "r", encoding="utf-8") as f:  # Windows 编码适配（utf-8）
                tasks_data = json.load(f)
            
            if not isinstance(tasks_data, list):
                raise ValueError("JSON格式错误：需为数组类型")
            
            success_count = 0
            for task in tasks_data:
                required_fields = ["task_name", "start_date", "end_date"]
                if not all(field in task for field in required_fields):
                    continue
                
                # 补全默认值
                task.setdefault("priority", "中")
                task.setdefault("owner", "未指定")
                task.setdefault("status", "未开始")
                task.setdefault("progress", 0)
                task.setdefault("description", "")
                task.setdefault("dependency", "")
                
                create_task(project_id=int(project_id), **task)
                success_count += 1
            
            self.on_task_operate("import")
            messagebox.showinfo("导入成功", f"共导入 {success_count} 个任务（跳过 {len(tasks_data)-success_count} 个无效任务）", parent=self)
        except Exception as e:
            messagebox.showerror("导入失败", f"JSON解析错误：{str(e)}", parent=self)

    def _on_search_focus_in(self, event):
        """搜索框获得焦点时的处理"""
        if self.search_entry.get() == "搜索任务名称/描述...":
            self.search_entry.delete(0, 'end')
            self.search_entry.configure(foreground='#000000')  # 恢复黑色文字
    
    def _on_search_focus_out(self, event):
        """搜索框失去焦点时的处理"""
        if not self.search_entry.get():
            self.search_entry.insert(0, "搜索任务名称/描述...")
            self.search_entry.configure(foreground='#808080')  # 浅灰色文字
    
    def _on_search_input(self, event):
        """搜索输入事件（实时过滤）"""
        self._apply_filter()

    def _on_task_select(self, event):
        """处理任务选择事件：根据选择数量更新按钮状态"""
        selected_items = self.task_tree.selection()
        if len(selected_items) == 1:
            # 选择单个任务：启用编辑和删除按钮
            self.edit_btn.config(state=NORMAL)
            self.delete_btn.config(state=NORMAL)
            self.batch_edit_btn.config(state=NORMAL)
        elif len(selected_items) > 1:
            # 选择多个任务：禁用编辑按钮，启用删除和批量修改按钮
            self.edit_btn.config(state=DISABLED)
            self.delete_btn.config(state=NORMAL)
            self.batch_edit_btn.config(state=NORMAL)
        else:
            # 未选择任务：禁用所有按钮
            self.edit_btn.config(state=DISABLED)
            self.delete_btn.config(state=DISABLED)
            self.batch_edit_btn.config(state=DISABLED)
